package com.xique.door.project.miniprogram.controller;

import com.alibaba.fastjson.JSONObject;
import com.xique.common.core.web.domain.AjaxResult;
import com.xique.door.bean.domain.Area;
import com.xique.door.project.miniprogram.bean.request.MiniAreaCodeListRequest;
import com.xique.door.project.miniprogram.bean.vo.LocationVo;
import com.xique.door.project.miniprogram.biz.service.IMiniLocationService;
import com.xique.door.service.IAreaService;
import com.xique.door.util.BaiduMapGeocoderUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;

@RestController
@RequestMapping("/homelocation")
public class MiniLocationController {

    @Autowired
    private IMiniLocationService miniLocationService;

    @Autowired private IAreaService tAreaService;

    /**
     * 根据定位获取最近小区
     */
    @GetMapping("/location")
    public AjaxResult seleceteDistance(BigDecimal lng, BigDecimal lat) {
        if (lng == null || lat == null) {
            return AjaxResult.error("经纬度为空");
        }
        return miniLocationService.seleceteDistance(lng, lat);
    }

    @GetMapping("/area")
    public AjaxResult seleceteArea(BigDecimal lng, BigDecimal lat) {
        if (lng == null || lat == null) {
            return AjaxResult.error("经纬度为空");
        }
        return miniLocationService.seleceteArea(lng, lat);
    }

    @GetMapping("/baiduApiArea")
    public AjaxResult baiduApiArea(String lng, String lat) {
        if (lng == null || lat == null) {
            return AjaxResult.error("经纬度为空");
        }
        JSONObject resultObj = BaiduMapGeocoderUtil.getAddressInfoByLngAndLat(lng, lat);

        LocationVo vo = new LocationVo();
        String provinceName = String.valueOf(resultObj.get("province"));//省
        String cityName = String.valueOf(resultObj.get("city"));//市
        String districtName = String.valueOf(resultObj.get("district"));//区
        String district = String.valueOf(resultObj.get("adcode"));//区的code

        vo.setProvinceName(provinceName);
        vo.setCityName(cityName);
        vo.setDistrict(district);
        vo.setDistrictName(districtName);

        Area districtArea =tAreaService.selectAreaByCode(district);
        districtArea =tAreaService.selectAreaById(districtArea.getParentId());
        vo.setCity(districtArea.getAreaCode());

        districtArea =tAreaService.selectAreaById(districtArea.getParentId());
        vo.setProvince(districtArea.getAreaCode());
        vo.setCity(districtArea.getAreaCode());

        return AjaxResult.success(vo);
    }
}
